<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="概述 红黑树是一种自平衡二叉查找树,它相对于二叉查找树性能会更加高效(查找、删除、添加等操作需要O(log n),其中n为树中元素的个数),但实现较为复杂(需要保持自身的平衡). 性质  红黑树与二叉查找树不同,它的节点多了一个颜色属性,每个节点非黑即红,这也是它名字的由来. 红黑树的节点定义如以下代码:  123456789101112131415161718private static fin">
<meta property="og:type" content="article">
<meta property="og:title" content="红黑树那点事儿">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/16/2017-06-16-RedBlackTree/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="概述 红黑树是一种自平衡二叉查找树,它相对于二叉查找树性能会更加高效(查找、删除、添加等操作需要O(log n),其中n为树中元素的个数),但实现较为复杂(需要保持自身的平衡). 性质  红黑树与二叉查找树不同,它的节点多了一个颜色属性,每个节点非黑即红,这也是它名字的由来. 红黑树的节点定义如以下代码:  123456789101112131415161718private static fin">
<meta property="og:locale">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_example.svg">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/c/c8/Red-black_tree_insert_case_3.png">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_insert_case_5.png">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/5/56/Red-black_tree_insert_case_4.png">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/3/39/Red-black_tree_delete_case_2.png">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/d/d7/Red-black_tree_delete_case_4.png">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/c/c7/Red-black_tree_delete_case_3.png">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/3/30/Red-black_tree_delete_case_5.png">
<meta property="og:image" content="https://upload.wikimedia.org/wikipedia/commons/3/31/Red-black_tree_delete_case_6.png">
<meta property="article:published_time" content="2017-06-16T10:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="2017">
<meta property="article:tag" content="Algorithms">
<meta property="article:tag" content="Tree">
<meta property="article:tag" content="数据结构">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_example.svg">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/16/2017-06-16-RedBlackTree/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>红黑树那点事儿 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%80%A7%E8%B4%A8"><span class="nav-number">2.</span> <span class="nav-text">性质</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%8F%92%E5%85%A5"><span class="nav-number">3.</span> <span class="nav-text">插入</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B51"><span class="nav-number">3.1.</span> <span class="nav-text">情况1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B52"><span class="nav-number">3.2.</span> <span class="nav-text">情况2</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B53"><span class="nav-number">3.3.</span> <span class="nav-text">情况3</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B54"><span class="nav-number">3.4.</span> <span class="nav-text">情况4</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B55"><span class="nav-number">3.5.</span> <span class="nav-text">情况5</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81"><span class="nav-number">3.6.</span> <span class="nav-text">代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%A0%E9%99%A4"><span class="nav-number">4.</span> <span class="nav-text">删除</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B51-1"><span class="nav-number">4.1.</span> <span class="nav-text">情况1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B52-1"><span class="nav-number">4.2.</span> <span class="nav-text">情况2</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B53-1"><span class="nav-number">4.3.</span> <span class="nav-text">情况3</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B54-1"><span class="nav-number">4.4.</span> <span class="nav-text">情况4</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B55-1"><span class="nav-number">4.5.</span> <span class="nav-text">情况5</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%83%85%E5%86%B56"><span class="nav-number">4.6.</span> <span class="nav-text">情况6</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81-1"><span class="nav-number">4.7.</span> <span class="nav-text">代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-number">5.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/16/2017-06-16-RedBlackTree/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          红黑树那点事儿
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-06-16 18:00:00" itemprop="dateCreated datePublished" datetime="2017-06-16T18:00:00+08:00">2017-06-16</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" itemprop="url" rel="index"><span itemprop="name">数据结构</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/Tree/" itemprop="url" rel="index"><span itemprop="name">Tree</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><hr>
<p><code>红黑树</code>是一种<code>自平衡二叉查找树</code>,它相对于<code>二叉查找树</code>性能会更加高效(查找、删除、添加等操作需要<code>O(log n)</code>,其中<code>n</code>为树中元素的个数),但实现较为复杂(需要保持自身的平衡).</p>
<h3 id="性质"><a href="#性质" class="headerlink" title="性质"></a>性质</h3><hr>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_example.svg"></p>
<p><code>红黑树</code>与<code>二叉查找树</code>不同,它的节点多了一个颜色属性,每个节点非黑即红,这也是它名字的由来.</p>
<p><code>红黑树</code>的节点定义如以下代码: </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> RED = <span class="keyword">true</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> BLACK = <span class="keyword">false</span>;</span><br><span class="line"><span class="keyword">private</span> Node root;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> size = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> color = RED; <span class="comment">//颜色</span></span><br><span class="line">    <span class="keyword">private</span> Node parent, left, right;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> orderStatus = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> K key;</span><br><span class="line">    <span class="keyword">private</span> V value;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(K key, V value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.key = key;</span><br><span class="line">        <span class="keyword">this</span>.value = value;</span><br><span class="line">        <span class="keyword">this</span>.size = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>完整的代码我已经放在了我的<code>Gist</code>中,<a target="_blank" rel="noopener" href="https://gist.github.com/SylvanasSun/147672912cc5bc6da27e15528542877f">点击查看完整代码</a>.</p>
<p><code>红黑树</code>需要保证以下性质: </p>
<ol>
<li>每个节点的颜色非黑即红.</li>
</ol>
<ol start="2">
<li><strong>根节点的颜色为黑色.</strong></li>
</ol>
<ol start="3">
<li>所有叶子节点都为黑色(即NIL节点).</li>
</ol>
<ol start="4">
<li><p><strong>每个红色节点的两个子节点都必须为黑色(不能有两个连续的红节点).</strong></p>
</li>
<li><p><strong>从任一节点到其叶子的所有简单路径包含相同数量的黑色节点.</strong></p>
</li>
</ol>
<h3 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h3><hr>
<p><code>红黑树</code>的查找操作与<code>二叉查找树</code>一致(因为查找不会影响树的结构),而插入与删除操作需要在最后对树进行调整.</p>
<p>我们将新的节点的颜色设为红色(如果设为黑色会使根节点到叶子的一条路径上多了一个黑节点,违反了性质5,这个是很难调整的).</p>
<p>现在我们假设新节点为<code>N</code>,它的父节点为<code>P</code>(且<code>P</code>为<code>G</code>的左节点,如果为右节点则与其操作互为镜像),祖父节点为<code>G</code>,叔叔节点为<code>U</code>.插入一个节点会有以下种情况.</p>
<h4 id="情况1"><a href="#情况1" class="headerlink" title="情况1"></a>情况1</h4><p><strong><code>N</code>位于根,它没有父节点与子节点,这时候只需要把它重新设置为黑色即可</strong>,无需其他调整.</p>
<h4 id="情况2"><a href="#情况2" class="headerlink" title="情况2"></a>情况2</h4><p><strong><code>P</code>的颜色为黑色</strong>,这种情况下保持了性质4(<code>N</code>只有两个叶子节点,它们都为黑色)与性质5(<code>N</code>是一个红色节点,不会对其造成影响)的有效,所以<strong>无需调整</strong>.</p>
<h4 id="情况3"><a href="#情况3" class="headerlink" title="情况3"></a>情况3</h4><p>如果<code>P</code>与<code>U</code>都为红色,我们可以将它们两个重新绘制为黑色,然后将<code>G</code>绘制为红色(保持性质5),最后再从<code>G</code>开始继续向上进行调整.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Red-black_tree_insert_case_3.png"></p>
<h4 id="情况4"><a href="#情况4" class="headerlink" title="情况4"></a>情况4</h4><p><strong><code>P</code>为红色,<code>U</code>为黑色,且<code>N</code>为<code>P</code>的左子节点,这种情况下,我们需要在<code>G</code>处进行一次<code>右旋转</code></strong>,结果满足了性质4与性质5,因为通过这三个节点中任何一个的所有路径以前都通过祖父节点<code>G</code>，现在它们都通过以前的父节点<code>P</code>.</p>
<p>关于旋转操作,可以查看这篇文章<a target="_blank" rel="noopener" href="http://sylvanassun.github.io/2017/03/30/red_black_binary_search_tree/">《Algorithms,4th Edition》读书笔记-红黑二叉查找树</a>.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_insert_case_5.png"></p>
<h4 id="情况5"><a href="#情况5" class="headerlink" title="情况5"></a>情况5</h4><p><code>P</code>为红色,<code>U</code>为黑色,且<code>N</code>为<code>P</code>的右子节点,我们需要先在<code>P</code>处进行一次<code>左旋转</code>,这样就又回到了情况4.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/5/56/Red-black_tree_insert_case_4.png"></p>
<h4 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fixAfterInsertion</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">while</span> (x != <span class="keyword">null</span> &amp;&amp; x != root &amp;&amp; colorOf(parentOf(x)) == RED) &#123;</span><br><span class="line">          <span class="keyword">if</span> (parentOf(x) == grandpaOf(x).left) &#123;</span><br><span class="line">              x = parentIsLeftNode(x);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              x = parentIsRightNode(x);</span><br><span class="line">          &#125;</span><br><span class="line">          fixSize(x);</span><br><span class="line">      &#125;</span><br><span class="line">      setColor(root, BLACK);</span><br><span class="line">  &#125;</span><br><span class="line">	</span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">parentIsLeftNode</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      Node xUncle = grandpaOf(x).right;</span><br><span class="line"><span class="comment">// 情况3</span></span><br><span class="line">      <span class="keyword">if</span> (colorOf(xUncle) == RED) &#123;</span><br><span class="line">          x = uncleColorIsRed(x, xUncle);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	<span class="comment">// 情况5</span></span><br><span class="line">          <span class="keyword">if</span> (x == parentOf(x).right) &#123;</span><br><span class="line">              x = parentOf(x);</span><br><span class="line">              rotateLeft(x);</span><br><span class="line">          &#125;</span><br><span class="line">	<span class="comment">// 情况4</span></span><br><span class="line">          rotateRight(grandpaOf(x));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">parentIsRightNode</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      Node xUncle = grandpaOf(x).left;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (colorOf(xUncle) == RED) &#123;</span><br><span class="line">          x = uncleColorIsRed(x, xUncle);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (x == parentOf(x).left) &#123;</span><br><span class="line">              x = parentOf(x);</span><br><span class="line">              rotateRight(x);</span><br><span class="line">          &#125;</span><br><span class="line">          rotateLeft(grandpaOf(x));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">uncleColorIsRed</span><span class="params">(Node x, Node xUncle)</span> </span>&#123;</span><br><span class="line">      setColor(parentOf(x), BLACK);</span><br><span class="line">      setColor(xUncle, BLACK);</span><br><span class="line">      setColor(grandpaOf(x), RED);</span><br><span class="line">      x = grandpaOf(x);</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;	</span><br></pre></td></tr></table></figure>
<h3 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h3><p>我们只考虑删除节点只有一个子节点的情况,且只有后继节点与删除节点都为黑色(如果删除节点为红色,从根节点到叶子节点的每条路径上少了一个红色节点并不会违反<code>红黑树</code>的性质,而如果后继节点为红色,只需要将它重新绘制为黑色即可).</p>
<p>先将删除节点替换为后继节点,且后继节点定义为<code>N</code>,它的兄弟节点为<code>S</code>.</p>
<h4 id="情况1-1"><a href="#情况1-1" class="headerlink" title="情况1"></a>情况1</h4><p><code>N</code>为新的根节点,在这种情况下只需要把根节点保持为黑色即可.</p>
<h4 id="情况2-1"><a href="#情况2-1" class="headerlink" title="情况2"></a>情况2</h4><p><strong><code>S</code>为红色,只需要在<code>P</code>进行一次<code>左旋转</code></strong>,接下来则<strong>继续按以下情况进行处理</strong>(尽管路径上的黑色节点数量没有改变,但<code>N</code>有了一个黑色的兄弟节点与红色的父节点).</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Red-black_tree_delete_case_2.png"></p>
<h4 id="情况3-1"><a href="#情况3-1" class="headerlink" title="情况3"></a>情况3</h4><p><code>S</code>和它的子节点都是黑色的,而<code>P</code>为红色.这种情况下只需要将<code>S</code>与<code>P</code>的颜色进行交换</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/d/d7/Red-black_tree_delete_case_4.png"></p>
<h4 id="情况4-1"><a href="#情况4-1" class="headerlink" title="情况4"></a>情况4</h4><p><strong><code>S</code>和它的子节点都是黑色的,这种情况下需要把<code>S</code>重新绘制为红色</strong>.这时不通过<code>N</code>的路径都将少一个黑色节点(通过<code>N</code>的路径因为删除节点是黑色的也都少了一个黑色节点),这让它们平衡了起来.</p>
<p>但现在通过<code>P</code>的路径比不通过<code>P</code>的路径都少了一个黑色节点,所以还需要在<code>P</code>上继续进行调整.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/c/c7/Red-black_tree_delete_case_3.png"></p>
<h4 id="情况5-1"><a href="#情况5-1" class="headerlink" title="情况5"></a>情况5</h4><p><strong><code>S</code>为黑色,它的左子节点为红色,右子节点为黑色.这种情况下,我们在<code>S</code>上做<code>右旋转</code></strong>,这样<code>S</code>的左儿子成为<code>S</code>的父亲和N的新兄弟。我们接着交换<code>S</code>和它的新父亲的颜色。所有路径仍有同样数目的黑色节点，但是现在<code>N</code>有了一个右儿子是红色的黑色兄弟，所以我们进入了情况6。<code>N</code>和<code>P</code>都不受这个变换的影响。</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/3/30/Red-black_tree_delete_case_5.png"></p>
<h4 id="情况6"><a href="#情况6" class="headerlink" title="情况6"></a>情况6</h4><p><strong><code>S</code>是黑色，它的右子节点是红色,我们在<code>N</code>的父亲<code>P</code>上做<code>左旋转</code></strong>.这样<code>S</code>成为<code>N</code>的父亲和<code>S</code>的右儿子的父亲。我们接着交换<code>N</code>的父亲和<code>S</code>的颜色，<strong>并使<code>S</code>的右儿子为黑色</strong>。子树在它的根上的仍是同样的颜色,但是,<code>N</code>现在增加了一个黑色祖先.所以,通过<code>N</code>的路径都增加了一个黑色节点.此时,如果一个路径不通过<code>N</code>,则有两种可能性:</p>
<ul>
<li>它通过<code>N</code>的新兄弟.那么它以前和现在都必定通过<code>S</code>和<code>N</code>的父亲,而它们只是交换了颜色.所以路径保持了同样数目的黑色节点.</li>
</ul>
<ul>
<li>它通过<code>N</code>的新叔父,<code>S</code>的右儿子.那么它以前通过<code>S</code>、<code>S</code>的父亲和<code>S</code>的右儿子,但是现在只通过<code>S</code>,它被假定为它以前的父亲的颜色,和<code>S</code>的右儿子,它被从红色改变为黑色.合成效果是这个路径通过了同样数目的黑色节点.</li>
</ul>
<p>在任何情况下,在这些路径上的黑色节点数目都没有改变.所以我们恢复了性质4.在示意图中的白色节点可以是红色或黑色,但是在变换前后都必须指定相同的颜色.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/3/31/Red-black_tree_delete_case_6.png"></p>
<h4 id="代码-1"><a href="#代码-1" class="headerlink" title="代码"></a>代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fixAfterDeletion</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">while</span> (x != <span class="keyword">null</span> &amp;&amp; x != root &amp;&amp; colorOf(x) == BLACK) &#123;</span><br><span class="line">          <span class="keyword">if</span> (x == parentOf(x).left) &#123;</span><br><span class="line">              x = successorIsLeftNode(x);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              x = successorIsRightNode(x);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      setColor(x, BLACK);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">successorIsLeftNode</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      Node brother = parentOf(x).right;</span><br><span class="line"><span class="comment">// 情况2</span></span><br><span class="line">      <span class="keyword">if</span> (colorOf(brother) == RED) &#123;</span><br><span class="line">          rotateLeft(parentOf(x));</span><br><span class="line">          brother = parentOf(x).right;</span><br><span class="line">      &#125;</span><br><span class="line"><span class="comment">// 情况3,4</span></span><br><span class="line">      <span class="keyword">if</span> (colorOf(brother.left) == BLACK &amp;&amp; colorOf(brother.right) == BLACK) &#123;</span><br><span class="line">          x = brotherChildrenColorIsBlack(x, brother);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	<span class="comment">// 情况5</span></span><br><span class="line">          <span class="keyword">if</span> (colorOf(brother.right) == BLACK) &#123;</span><br><span class="line">              rotateRight(brother);</span><br><span class="line">              brother = parentOf(x).right;</span><br><span class="line">          &#125;</span><br><span class="line">	<span class="comment">// 情况6</span></span><br><span class="line">          setColor(brother.right, BLACK);</span><br><span class="line">          rotateLeft(parentOf(x));</span><br><span class="line">          x = root;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">brotherChildrenColorIsBlack</span><span class="params">(Node x, Node brother)</span> </span>&#123;</span><br><span class="line">      setColor(brother, RED);</span><br><span class="line">      x = parentOf(x);</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><ul>
<li><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E7%BA%A2%E9%BB%91%E6%A0%91">Wikipedia</a></li>
</ul>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/2017/" rel="tag"># 2017</a>
              <a href="/yuwanzi.io/tags/Algorithms/" rel="tag"># Algorithms</a>
              <a href="/yuwanzi.io/tags/Tree/" rel="tag"># Tree</a>
              <a href="/yuwanzi.io/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="tag"># 数据结构</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/06/14/2017-06-14-sort_algorithms_qucikSort/" rel="prev" title="深入浅出排序算法(3)-快速排序">
                  <i class="fa fa-chevron-left"></i> 深入浅出排序算法(3)-快速排序
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2017/06/27/2017-06-27-DynamicProgramming/" rel="next" title="什么是动态规划?">
                  什么是动态规划? <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
